package com.dashu.device.util;

import com.dashu.device.bean.CQ.CQBaseReq;
import com.dashu.device.bean.CQ.CQBaseResp;
import com.dashu.device.bean.CQ.CQData;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CQWriteUtil {

    /**
     * 组装返回
     *
     * @param cmd
     * @param req
     * @param body
     * @return
     */
    public static CQBaseResp response(int cmd, CQBaseResp req, Object body) {
        CQBaseResp comparedBaseResp = new CQBaseResp();
        comparedBaseResp.setSn(req.getSn());
        comparedBaseResp.setBody(body);
        comparedBaseResp.setCmd(cmd);
        comparedBaseResp.setSession(req.getSession());

        log.info("response:" + comparedBaseResp.toString());
        return comparedBaseResp;
    }

    /**
     * 组装返回
     *
     * @param cmd
     * @param sn
     * @param body
     * @return
     */
    public static CQBaseReq request(int cmd, String sn, Object body, Object... reason) {
        String session = getSession();
        CQBaseReq comparedBaseReq = new CQBaseReq();
        comparedBaseReq.setSn(sn);
        comparedBaseReq.setBody(body);
        comparedBaseReq.setCmd(cmd);
        comparedBaseReq.setSession(session);

        CQData deviceData = new CQData();
        deviceData.setSession(session);
        deviceData.setStatus(true);
        deviceData.setReqType(cmd);
        if (reason != null && reason.length > 0 && reason[0] != null)
            deviceData.setReason(reason);

        log.info("request:" + comparedBaseReq.toString());
        return comparedBaseReq;
    }

    private int cqMark;
    private static int session = 0;

    private static String getSession() {
        session++;
        if (session > 255)
            session = 1;
        String sess = Integer.toHexString(session & 0xFF).toUpperCase();
        if (sess.length() == 1)
            sess = "0" + sess;
        return sess;
    }

    public static void send(ChannelHandlerContext ctx, String msg) {
        System.out.println(msg);
        ctx.writeAndFlush(Unpooled.copiedBuffer(msg + "\n", CharsetUtil.UTF_8)).addListener((ChannelFutureListener) channelFuture -> {
            if (channelFuture.isDone() && channelFuture.isSuccess()) {
                log.info("Send:发送数据到终端成功");
            } else {
                log.info("Send:发送数据到终端失败");
            }
        });
    }
}
